<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 提示文本条 -->
      <el-row>
        <el-col>
          <el-alert
            center
            title="注意：只可以修改第三级分类的参数！"
            type="warning"
            :closable="false"></el-alert>
        </el-col>
      </el-row>

      <!-- 级联选择器区域 -->
      <el-form label-width="100px">
        <el-form-item label="选择商品分类:">
          <!-- options 是数据源 -->
          <!-- props 用来指向配置一个对象，即peizhiProps -->
          <!-- v-model 绑定选择的 ID 数组 -->
          <el-cascader
            v-model="selectIds"
            :options="cateList"
            :props="peizhiProps"
            @change="selectChange"
            clearable
            filterable
            placeholder="试试搜索"
            size="medium"></el-cascader>
        </el-form-item>
      </el-form>

      <!-- 标签页区域 -->
      <el-tabs type="border-card" v-model="activeName" @tab-click="getParamsList">
        <!-- 动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加按钮 -->
          <el-button
            size="mini"
            type="primary"
            :disabled="isDisabled"
            @click="addDialogVisible = true">
            添加参数
          </el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyParamsList" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand" label=">">
              <template slot-scope="props">
                <!-- 展开表格 -->
                <el-row>
                  <!-- tag 标签渲染区域 -->
                  <el-tag
                    v-for="(item, i) in props.row.attr_vals"
                    :key="i"
                    closable
                    @close="dltParamsTag(i, props.row)">
                    {{ item }}
                  </el-tag>
                  <!-- 添加 tag 区域 -->
                  <el-input
                    class="input-new-tag"
                    v-if="props.row.inputVisible"
                    v-model="props.row.inputValue"
                    ref="tagInputRef"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(props.row)"
                    @blur="handleInputConfirm(props.row)"></el-input>
                  <el-button v-else size="small" @click="showInput(props.row)">添加标签</el-button>
                </el-row>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <!-- 参数名称列 -->
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <!-- 操作列 -->
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)">
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加按钮 -->
          <el-button
            size="mini"
            type="primary"
            :disabled="isDisabled"
            @click="addDialogVisible = true">
            添加属性
          </el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyParamsList" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand" label=">">
              <template slot-scope="props">
                <!-- 展开表格 -->
                <el-row>
                  <!-- tag 标签渲染区域 -->
                  <el-tag
                    v-for="(item, i) in props.row.attr_vals"
                    :key="i"
                    closable
                    @close="dltParamsTag(props)">
                    {{ item }}
                  </el-tag>
                </el-row>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <!-- 属性名称列 -->
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <!-- 操作列 -->
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)">
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数和属性的对话框 -->
    <el-dialog
      :title="'添加' + dialogText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="closeDialog">
      <!-- 添加表单 -->
      <el-form :model="addForm" :rules="formRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="dialogText + '名称：'" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addPrams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数和属性的对话框 -->
    <el-dialog
      :title="'修改' + dialogText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="closeEdDlog">
      <!-- 修改表单 -->
      <el-form :model="editForm" :rules="formRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="dialogText + '名称：'" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editPrams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类列表
      cateList: [],
      // 联动选择器配置对象
      peizhiProps: {
        // value 表示选中的值,指向选择ID
        value: 'cat_id',
        // label 表示选择显示名称
        label: 'cat_name',
        // children 表示子节点
        children: 'children',
        // 表示通过 hover 显示子级
        expandTrigger: 'hover',
        // 只能选一项
        checkStrictly: false,
      },
      // 选择到的分类的ID数组
      selectIds: [],
      // 选中的标签页的name（请求参数）
      activeName: 'many',
      // 动态参数列表数据
      manyParamsList: [],
      // 静态属性列表数据
      onlyParamsList: [],
      // 添加按钮是否禁用
      isDisabled: true,
      // 控制添加对话框显示隐藏
      addDialogVisible: false,
      // 表单验证规则
      formRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      },
      // 添加表单绑定对象
      addForm: {
        // 添加的名称
        attr_name: '',
      },
      // 控制编辑对话框的显示隐藏
      editDialogVisible: false,
      // 编辑表单数据源
      editForm: {},
    }
  },
  computed: {
    // 计算对话框标题
    dialogText() {
      if (this.activeName == 'many') {
        return '参数'
      } else {
        return '属性'
      }
    },
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 请求分类列表数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 3 },
      })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },
    // 选择选项发生改变时触发
    selectChange() {
      // console.log(this.selectIds)
      if (this.selectIds.length !== 3) {
        this.selectIds = []
        this.manyParamsList = []
        this.onlyParamsList = []
        return
      }
      this.isDisabled = false
      this.getParamsList()
    },
    // 请求参数列表数据
    async getParamsList() {
      if (this.selectIds.length < 3) return
      const { data: res } = await this.$http.get(`categories/${this.selectIds[2]}/attributes`, {
        params: { sel: this.activeName },
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      } else {
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
          // 控制文本框隐藏
          item.inputVisible = false
          // 控制文本框文字为空
          item.inputValue = ''
        })
        // console.log(res.data)
        if (this.activeName === 'many') {
          this.manyParamsList = res.data
        } else {
          this.onlyParamsList = res.data
        }
      }
    },
    // 提交添加 参数 或 属性
    addPrams() {
      this.$refs.addFormRef.validate(async value => {
        if (!value) return
        const { data: res } = await this.$http.post(`categories/${this.selectIds[2]}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName,
        })
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getParamsList()
        this.addDialogVisible = false
      })
    },
    // 当对话框关闭时触发
    closeDialog() {
      this.$refs.addFormRef.resetFields()
    },
    // 关闭编辑对话框触发
    closeEdDlog() {
      this.$refs.editFormRef.resetFields()
    },
    // 显示编辑对话框
    showEditDialog(row) {
      // console.log(row)
      this.editForm = row
      this.editDialogVisible = true
    },
    // 编辑动态参数或静态属性
    editPrams() {
      this.$refs.editFormRef.validate(async value => {
        if (!value) return
        // console.log(this.editForm)
        const { data: res } = await this.$http.put(
          `categories/${this.editForm.cat_id}/attributes/${this.editForm.attr_id}`,
          this.editForm
        )
        // console.log(res)
        // console.log(this.editForm)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getParamsList()
        this.editDialogVisible = false
      })
    },
    // 删除动态参数或静态属性
    deleteParams(row) {
      // 警告弹框
      this.$confirm('是否确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${row.cat_id}/attributes/${row.attr_id}`
          )
          // console.log(res)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          // this.getRolesList()
          this.getParamsList()
        })
        .catch(() => this.$message.info('已取消删除'))
    },
    // 删除参数或属性的 tag 标签
    dltParamsTag(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveTagToDB(row)
    },
    // 添加、删除 tag 的共用请求方法
    async saveTagToDB(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.selectIds[2]}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(','),
        }
      )
      if (res.meta.status !== 200) return $this.$message.error(res.meta.msg)
      return this.$message.success(res.meta.msg)
    },
    // 添加 tag 标签处理函数
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveTagToDB(row)
    },
    // 显示添加 tag 标签输入框
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.tagInputRef.$refs.input.focus()
      })
    },
  },
}
</script>

<style lang="less" scoped>
.el-form {
  margin-top: 15px;
}

.el-cascader {
  width: 250px;
  z-index: 999;
}

.el-tag {
  margin: 10px;
}

.input-new-tag {
  width: 200px;
}
</style>
